package com.boot.config;

import com.boot.common.property.SecurityProperties;
import com.boot.filter.JwtAuthFilter;
import com.boot.filter.RateLimiterFilter;
import com.boot.modules.auth.service.CustomUserDetailsService;
import com.boot.system.service.ConfigService;
import com.boot.util.JwtUtil;
import com.boot.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Autowired
    ConfigService configService;

    @Autowired
    JwtUtil jwtUtil;

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    CustomUserDetailsService customUserDetailsService;

    @Autowired
    SecurityProperties securityProperties;

    /**
     * 强散列哈希加密实现
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * AuthenticationManager 手动注入
     * @param config 认证配置
     */
    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception {
        return config.getAuthenticationManager();
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        //忽略白名单
        http.authorizeHttpRequests(requestMatcherRegistry -> requestMatcherRegistry.requestMatchers(
                        securityProperties.getIgnoreUrls()).permitAll()
                .anyRequest().authenticated()
        );
        http
                //由于使用的是JWT，我们这里不需要csrf
                .csrf(AbstractHttpConfigurer::disable)
                //禁用session
                .sessionManagement(configurer -> configurer.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
        //IP限流过滤器
        http.addFilterBefore(new RateLimiterFilter(redisUtil, configService), UsernamePasswordAuthenticationFilter.class);
        //JWT校验过滤器
        http.addFilterBefore(new JwtAuthFilter(jwtUtil, redisUtil, customUserDetailsService, securityProperties), UsernamePasswordAuthenticationFilter.class);
        return http.build();
    }

}